package com.industry.framework.core.generic.record;

import com.industry.framework.common.redis.RedisUtils;
import com.industry.framework.core.annountions.record.IdooRecordBizType;
import com.industry.framework.core.context.CoreApplicationContext;
import com.industry.framework.core.generic.mapper.RecordTempMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class RecordBuilder {
    private static final Logger log = LoggerFactory.getLogger(RecordBuilder.class);

    public static String REDISSION_CACHE_PREFIX = "RECORD_CACHE_PREFIX::";

    //判断字段是否需要记录
    public static RecordScanner.RecordPropertyFields getRecordPropertyField(Class<?> clz , String fieldStr){
        if(!hasTargetOperationRecod(clz)){
            return null;
        }
        return RecordScanner.cacheRecordMap.get(clz).stream()
                .filter(i-> {
                    return StringUtils.equals(i.getFieldName(), fieldStr);
                })
                .findFirst()
                .orElse(null);
    }

    //获取目标表名
    public static String findTargetTable(Class<?> clz){
        if(hasTargetOperationRecod(clz)){
            //先从redis中获取
            Object cacheObject = RedisUtils.getCacheObject(REDISSION_CACHE_PREFIX + clz.getName());
            if(ObjectUtils.isEmpty(cacheObject)) {
                //没有找到重新构建
                IdooRecordBizType annotation = clz.getAnnotation(IdooRecordBizType.class);
                String tableName = StringUtils.isEmpty(annotation.value()) ? buildTableName(clz) : annotation.value();
                boolean table = createTable(tableName);
                //构建成功后进缓存
                if(table){
                    RedisUtils.setCacheObject(REDISSION_CACHE_PREFIX + clz.getName(),tableName);
                }
                return tableName;
            }
            log.info("【IDOO-RECOREBUILDER】已存在操作记录表，KEY：{},",REDISSION_CACHE_PREFIX + clz.getName());
            return String.valueOf(cacheObject);
        }
        return null;
    }


    //是否注册了操作记录业务
    public static boolean hasTargetOperationRecod(Class<?> clz){
        return  RecordScanner.cacheRecordMap.containsKey(clz);
    }

    //根据实体构造操作记录表
    public static String buildTableName(Class<?> clz){
        return clz.getSimpleName().toLowerCase() + "_record";
    }
//
    public static boolean createTable(String tableName){
        boolean record = true;
        //TODO 先看下是否存在该表，不存在则创建表
        RecordTempMapper rm = CoreApplicationContext.getApplicationContext().getBean(RecordTempMapper.class);
        try{
            rm.createTableIfNotExists(tableName);
        }catch (Exception e){
            log.error("【IDOO-CREATE RECORD TABLE ERROR】 CAUSE : TABLENAME:{}",tableName);
            record = false;
        }
        return record;
    }



}
